package com.kfm.web.servlet;

import com.kfm.web.mapper.IUserinfoMapper;
import com.kfm.web.model.Userinfo;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@WebServlet({"/login"})
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        Userinfo userinfo = new Userinfo();
        userinfo.setUsername(username);
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("md5");
            md5.update(password.getBytes());
            byte[] digest = md5.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            password = sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        userinfo.setPassword(password);

        SqlSessionFactory factory = (SqlSessionFactory) getServletContext().getAttribute("factory");

        SqlSession sqlSession = factory.openSession();

        IUserinfoMapper mapper = sqlSession.getMapper(IUserinfoMapper.class);

        List<Userinfo> userinfos = mapper.selectByUserinfo(userinfo);

        if (userinfos != null && userinfos.size() == 1){
            // 登录成功
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("登录成功");
        } else{
            // 用户名或密码错误
            req.setAttribute("msg", "用户名或密码错误");
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        }
    }
}
